<template>
  <section>
    <!-- 工具条：高级查询 + 添加 -->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="queryParams">
        <el-form-item>
          <!--
            el-input -- 输入框
               v-model="queryParams.keyword"    -- 双向绑定
               placeholder="姓名"               -- 提示语
            el-button -- 按钮
              type="primary"                    -- 颜色
              v-on:click="queryBykeyword"       -- 绑定单击事件
          -->
          <el-input v-model="queryParams.keyword" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="queryBykeyword">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!-- 列表展示-->
    <!-- 分页列表 -->
    <el-table :data="pageParams.departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="名称" width="180" sortable>
      </el-table-column>
      <el-table-column prop="sn" label="编号" width="180" sortable>
      </el-table-column>
      <el-table-column prop="dirPath" label="路径" width="180" sortable>
      </el-table-column>
      <el-table-column label="状态" width="150">
        <template scope="scope">
          <!-- scope.row.state
            通过scope.row获取当前行的对象 = json对象
           -->
          <span style="color: #11b95c" v-if="scope.row.state==1">启用</span>
          <span style="color: red" v-else>禁用</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="部门经理" width="180" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" width="180" sortable>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 工具条：批量删除 + 分页栏 -->
    <el-col :span="24" class="toolbar">
      <!--
          :disabled="this.sels.length===0" - 至少选中一行，才可以点击
      -->
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="queryParams.pageSize" :total="pageParams.totals" :current-page="queryParams.currentPage" style="float:right;">
      </el-pagination>
    </el-col>

    <!-- 添加或修改的模态框-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="编号" prop="sn">
          <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="启用状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门经理">
          <el-select v-model="saveForm.manager" value-key="id" placeholder="请选择">
            <el-option
                v-for="emp in managers"
                :label="emp.username"
                :value="emp">
              <span style="float: left">{{ emp.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ emp.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader v-model="saveForm.parent"
                       :options="deptTree"
                       :props="{
                checkStrictly: true,
                label: 'name', //级联框显示那个属性的值
                value: 'id'   //点击提交按钮发送请求的时候传递的参数
              }"
                       clearable>
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
export default {
  data() {
    return {
      //分页参数：分页列表 + 分页栏所需数据
      pageParams:{
        departments: [],    //分页列表中：:data - 显示分页数据
        totals: 0           //总页数：分页栏中显示 - 计算分页栏的
      },

      //定义查询参数：分页查询 + 高级查询
      queryParams:{
        pageSize: 5,      //分页查询参数：每页显示的条数 or 分页栏中显示
        currentPage: 1,   //分页查询参数：当前页 or 分页栏中显示
        keyword: ''       //高级查询参数：关键字查询
      },

      //列表忙等框
      listLoading: false,
      //批量删除 - 保存选中的列
      sels: [],//列表选中列

      title:"保存", //添加和修改的模态框的标题
      saveFormVisible: false,//添加和修改的模态框默认不显示
      saveLoading: false, //保存模态框 - 默认不显示
      saveFormRules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        sn: [
          { required: true, message: '请输入编号', trigger: 'blur' }
        ]
      },
      //编辑界面数据
      saveForm: {
        id: null,
        sn: null,
        name: null,
        state: 1, //默认启用
        manager: null,
        parent: null
      },

      managers:[], //保存所有的经理 - 员工
      deptTree:[] //加载部门树
    }
  },
  methods: {
    //性别显示转换
    formatSex: function (row, column) {
      return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
    },

    //高级查询 - ok
    queryBykeyword(){
      this.queryParams.currentPage = 1;
      this.getDepartments();
    },

    //点击分页逻辑 - ok
    handleCurrentChange(val) {
      this.queryParams.currentPage = val;
      this.getDepartments();
    },

    //获取部门分页列表 -ok
    getDepartments() {
      this.listLoading = true; //显示忙等框
      this.$http.post("/department",this.queryParams)
          .then(res => {
            //成功之后的回调函数
            this.pageParams.totals = res.data.totals;
            this.pageParams.departments = res.data.data;
            this.listLoading = false;//关闭忙等框
          }).catch(res => {
        this.$message.error('系统错误,请稍后重试');
      })
    },

    //删除 - ok
    handleDel: function (index, row) {
      //确认框
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {  //点击确定之后的操作
        this.listLoading = true; //显示忙等框
        this.$http.delete("/department/" + row.id)
            .then(res => { //成功之后的回调
              this.listLoading = false; //关闭忙等框
              if(res.data.success){ //成功 200
                this.$message({   //删除成功之后的提示
                  message: "删除成功",
                  type: 'success'
                });
                this.getDepartments();    //重新加载数据
              }else{ //500
                this.$message({   //删除成功之后的提示
                  message: res.data.msg,
                  type: 'error'
                });
              }
            }).catch(res => { //失败之后的回调
          this.$message.error('系统错误,请稍后重试');  //连不上后端代码或404，400
        })
      }).catch(() => {  //点击取消之后的操作
      });
    },

    //点击添加按钮弹出模态框
    handleAdd: function () {
      this.title = "添加";
      //重置
      this.saveForm = {
        id: null,
        sn: null,
        name: null,
        state: 1, //默认启用
        manager: null,
        parent: null
      };
      //加载所有的经理 - 员工
      this.getManagers();
      //加载部门树：
      this.getDeptTree();
      //显示模态框
      this.saveFormVisible = true;
    },
    //点击修改按钮弹出模态框
    handleEdit: function (index, row) {
      this.title = "修改";
      //克隆 - 回显
      this.saveForm = Object.assign({}, row);

      //点击修改操作对上级部门的回显做处理
      var dirPath = row.dirPath;
      var idArr = dirPath.split("/");
      var arr = [];
      for(var i=1;i<idArr.length-1;i++){
        var id = parseInt(idArr[i]);
        arr[i-1] = id;
      }
      this.saveForm.parent = arr;

      //加载所有的经理 - 员工
      this.getManagers();
      //加载部门树：
      this.getDeptTree();
      this.saveFormVisible = true; //显示模态框
    },
    //点击保存按钮提交到后端
    saveSubmit: function () {
      //提交验证 - 只要表单验证不通过都不能提交
      this.$refs.saveForm.validate((valid) => {
        //如果验证通过返回true，返回返回false
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            //显示忙等框
            this.saveLoading = true;

            //点击提交将提交的数据 格式转成  对象
            var arr = this.saveForm.parent; //[ 2, 5 ]
            this.saveForm.parent = {id:arr[arr.length-1]}

            //提交的数据
            let para = Object.assign({}, this.saveForm);

            this.$http.put("/department",para).then(res => {
              this.saveLoading = false;//关闭忙等框
              if(res.data.success){
                this.$message({
                  message: '操作成功',
                  type: 'success'
                });
                //重置表单
                // this.$refs['saveForm'].resetFields();
                this.saveFormVisible = false; //关闭模态框
                this.getDepartments();
              }else{
                this.$message({
                  message: res.data.msg,
                  type: 'error'
                });
                this.saveFormVisible = false; //关闭模态框
              }
            }).catch(res=>{
              this.$message.error('系统错误,请稍后重试');  //连不上后端代码或404，400
            })
          });
        }
      });
    },

    //批量删除 - 选中列的时候处罚 - ok
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除 - 真正的删除 -ok
    batchRemove: function () {
      //console.log(this.sels);//选中的行对象 - 集合
      //item - 就是集合中的每一个对象【json对象】
      var ids = this.sels.map(item => item.id);
      //console.log(this.sels.map(item => item.id));//[ 1, 2, 5, 7, 10 ]
      //console.log(ids);//1,2,5,7,10
      this.$confirm('确认删除选中记录吗？', '温馨提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/department",ids)
            .then(res => {
              this.listLoading = false;
              if(res.data.success){
                this.$message({   //删除成功之后的提示
                  message: '删除成功',
                  type: 'success'
                });
                this.queryParams.currentPage = 1;//批量删除之后都到第一页
                this.getDepartments();    //重新加载数据
              }else{
                this.$message({
                  message: res.data.msg,
                  type: 'error'
                });
              }
            }).catch(res => {
          this.$message.error('系统错误,请稍后重试');  //连不上后端代码或404
        })
      }).catch(() => { //点击取消之后的操作
      });
    },

    //加载所有的经理 - 员工
    getManagers(){
      this.$http.get("/employee").then(res => {
        this.managers = res.data;
      })
        .catch(res => {
          this.$message.error('获取经理失败,请稍后重试');
        })
    },
    //加载部门树
    getDeptTree(){
      this.$http.get("/department/deptTree").then(res => {
        this.deptTree = res.data;
      })
          .catch(res => {
            this.$message.error('获取部门树失败,请稍后重试');
          })
    }
  },
  mounted() {
    //页面一加载 - 获取分页数据
    this.getDepartments();
  }
}

</script>

<style scoped>

</style>